﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using Barbar.MapReport.DataSource.Resources;
using System.Xml.Serialization;
using System.Collections;

namespace Barbar.MapReport.DataSource {
  [XmlType(TypeName="ZoomLevels", Namespace = Constants.DataSourceXmlNamespace)]
  public class ZoomLevelCollection : Collection<ZoomLevel> {
    public const int MinGoogleZoomLevel = 0;
    public const int MaxGoogleZoomLevel = 18;

    private ZoomLevel[] m_ZoomLevelLookup;

    private void EnsureZoomLevelLookup() {
      if (m_ZoomLevelLookup == null) {
        m_ZoomLevelLookup = new ZoomLevel[MaxGoogleZoomLevel + 1];
        foreach (ZoomLevel zoomLevel in this) {
          for (int i = zoomLevel.GoogleMinimalZoom; i <= zoomLevel.GoogleMaximalZoom; i++) {
            m_ZoomLevelLookup[i] = zoomLevel;
          }
        }
        foreach (ZoomLevel zoomLevel in m_ZoomLevelLookup) {
          if (zoomLevel == null)
            throw new DataSourceException("ZoomLevelCollection is invalid.");
        }
      }
    }

    public ZoomLevel GetZoomLevel(int googleZoomLevel) {
      if (googleZoomLevel < MinGoogleZoomLevel || googleZoomLevel > MaxGoogleZoomLevel)
        throw new ArgumentOutOfRangeException("googleZoomLevel", googleZoomLevel, Translator.Error_InvalidZoomLevel);

      EnsureZoomLevelLookup();
      return m_ZoomLevelLookup[googleZoomLevel];
    }
  }
}
